<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>设置产品基础价格</title>
    <link rel="stylesheet" href="__PUBLIC__/laydata/layui/css/layui.css">
    <link rel="stylesheet" href="__PUBLIC__/laydata/css/date.css">
    <style>
        .addMoreTime{
            margin-top: 4px;
        }
        .package_price_input{
            border:1px solid red;
            width:80%;
        }
        .package_price_input,.currency_symbol{
            display: inline-block;
        }
        #test-n2 table td{
            height:80px !important;
            line-height: 30px;
        }
        .setBasePackage,.delBasePrice{
            float: right;
            margin-top: -4px;
            margin-right: 4px;
        }
        .updateSaleTime{
            margin-left: 0;
            margin-top: 5px;
        }
        #test-n2 .layui-laydate,#test-n2 .layui-laydate-main{
            width: 100% !important;
        }
        .noMarginLeft{
            margin-left: 0 !important;
        }
        .calendar_day{
            margin:0 10px !important;
            border-bottom: 1px solid #eee;
            height: 39px;
        }
        .calendar_price{
            color:#ff7d00 !important
        }
        .layui-this>span>.calendar_price{
            color:#fff !important
        }
        #showPackageData{
            min-height:200px;
            display: none;
        }
        .selectAll:hover,.selectAllCancel:hover{
            color:#1e9fff
        }
        .elem-quote-div{
            background-color: rgba(0, 150, 136, 0.5);
        }
        .package-list-div{
            background-color: rgba(255, 87, 34, 0.1) !important
        }
        .getPackagePrice,.getPriceByMonthAndPackageId{
            float: left;
        }
    </style>
</head>
<body>
<input type="hidden" name="product_id" value="{$product_id}" />
<!-- 你的HTML代码 -->
<div class="layui-container" style="padding: 15px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <blockquote class="layui-elem-quote elem-quote-div">
                <span>产品基础价格设置</span>
                <button class="layui-btn layui-btn-sm setBasePackage">设置套餐</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger delBasePrice">批量删除</button>
            </blockquote>
            <!--普通成本弹层-->
            <div id="setPriceShade">
                <form class="layui-form" action="" method="post" name="setPriceShade">
                    <input type="hidden" id="specs_ids" value="" />
                    <div class="layui-form-item">
                        <label class="layui-form-label">{:lang('售卖范围')}</label>
                        <div class="layui-input-inline layui-col-md8 noMarginLeft">
                            <input type="text" name="sale_time" value="{$product.sale_starttime|date='Y-m-d',###} - {$product.sale_endtime|date='Y-m-d',###}" class="layui-input sale_time" />
                        </div>
                        <!--<button class="layui-btn layui-btn-sm updateSaleTime">修改</button>-->
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">{:lang('货币类型')}</label>
                        <div class="layui-input-inline layui-col-md8 noMarginLeft">
                            <select name="currency" id="currency" lay-search="" lay-filter="currency" class="layui-select">
                                <option value="">请选择货币类型</option>
                                {volist name="currencyCodeList" id="value"}
                                <option value="{$value.currency_code}" {if !empty($product.currency)&&$product.currency==$value.currency_code}selected{/if}>{$value.currency_all_name}</option>
                                {/volist}
                            </select>
                        </div>
                        <!--<button class="layui-btn layui-btn-sm updateCurrency">{:lang('提交')}</button>-->
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">选择套餐</label>
                        <div class="layui-input-block layui-col-md8 noMarginLeft">
                            {if !empty($packageList)}
                            {volist name='packageList' id='package_v'}
                            <input type="radio" name="select_package_id" value="{$package_v['id']}" title="{$package_v['name']}" class="layui-input" lay-filter="change_package" />
                            {/volist}
                            {else}
                            <span style="line-height: 40px;color:red" class="layui-input-inline">请先设置套餐！</span>
                            {/if}
                        </div>
                    </div>
                    <!--库存日期-->
                    <div class="layui-form-item" id="selectSalesDataArr">
                        <label class="layui-form-label">库存日期</label>
                        <div class="layui-input-block layui-col-xs8 noMarginLeft" style="margin: 0;">
                            <input type="text" name="select_time" autocomplete="off" placeholder="库存日期" class="layui-input layui-input-inline select_time" />
                        </div>
                        <div class="layui-input-block layui-col-xs8" style="background: #eee;width:88%;margin-left:110px;">
                            <div style="width:100%;min-height:50px;" id="selectTimeArr">
                            </div>
                        </div>
                    </div>
                    <!--设置方式-->
                    <div class="layui-form-item " id="selectTimeForm">
                    </div>
                    <div class="layui-form-item " id="moreTimeForm" style="display: none;">
                        <label class="layui-form-label">特殊日期</label>
                        <div class="layui-input-block layui-col-xs8" style="margin: 0;">
                            <input type="text" name="moreTime" autocomplete='off' value="" placeholder="特殊日期" class="layui-input layui-input-inline singleDate" />
                        </div>
                        <div class="layui-input-block layui-col-xs8" style="background: #eee;width:88%;margin-left:110px;">
                            <div style="width:100%;min-height:50px;" id="moreTimeArr">
                            </div>
                        </div>
                    </div>


                </form>
                <div class="layui-form-item" style="display: none;" id="setBasePriceBody">
                    <label class="layui-form-label">设置价格</label>
                    <div class="layui-input-block layui-col-xs8" style="width:80%;margin-left:0;">
                        <table class="layui-table specsPriceSnap">
                            <thead>
                            <tr>
                                <th>{:lang('名称')}</th>
                                <th>{:lang('结算价')}</th>
                                <th>{:lang('建议销售价')}</th>
                                <th>{:lang('库存')}</th>
                                <th>{:lang('最低下单数')}</th>
                                <th>{:lang('最小增长数')}</th>
                            </tr>
                            </thead>
                            <tbody class="batch_person">

                            </tbody>
                        </table>
                    </div>
                    <button class="layui-input-block layui-btn submitPriceData">提交</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="__PUBLIC__/laydata/layui/layui.js"></script>
<script>
    var currency_symbol = "{$product.currency_symbol | default='￥'}";
    var basespec_url = "{:url('admin/product/getProductBaseSpecByPackageId')}";
    layui.use(['layer', 'form','jquery','laydate'], function() {
        var layer = layui.layer,
            $ = layui.jquery,
            laydate = layui.laydate,
            form = layui.form;
        laydate.render({     //创建时间选择框
            elem: '.sale_time' //指定元素
            ,range:true
            ,format: 'yyyy-MM-dd'
            ,position:'fixed'
            ,trigger:'click'
            ,done: function(value, date){
                //操作自动提交
                var product_id = $('input[name=product_id]').val();
                var sale_time = value.split(' - ');
                if(sale_time.length < 2){layer.msg('{:lang("请正确选择售卖日期")}');return false;}
                ajaxUpdateProductSaleTime(product_id,sale_time);
                return false;
            }
        });
        laydate.render({     //创建时间选择框
            elem: '.select_time' //指定元素
            ,range:true
            ,format: 'yyyy-MM-dd'
            ,min:'{$product.sale_starttime|date="Y-m-d",###}'
            ,max:'{$product.sale_endtime|date="Y-m-d",###}'
            ,position:'fixed'
            ,trigger:'click'
            ,done: function(value, date){
                var sale_time = value.split(' - ');
                if(sale_time.length < 2){layer.msg('{:lang("请正确设置选择日期")}');return false;}
                addNewSelectTime(value);
                return false;
            }
        });
        laydate.render({     //创建时间选择框
            elem: '.singleDate' //指定元素
            ,format: 'yyyy-MM-dd'
            ,min:'{$product.sale_starttime|date="Y-m-d",###}'
            ,max:'{$product.sale_endtime|date="Y-m-d",###}'
            ,position:'fixed'
            ,trigger:'click'
            ,done: function(value, date){
                if(value=='' || value==undefined){layer.msg('{:lang("请正确设置特殊日期")}');return false;}
                addNewMoreTime(value);
                return false;
            }
        });
        laydate.render({     //创建时间选择框
            elem: '.del_time' //指定元素
            ,range:true
            ,format: 'yyyy-MM-dd'
            // ,min:'{$product.sale_starttime|date="Y-m-d",###}'
            // ,max:'{$product.sale_endtime|date="Y-m-d",###}'
            ,trigger:'click'
        });
        //【普通成本】弹窗中时间段选择渲染
        function renderSelectTimeForm(){
            $('#selectTimeForm').children().remove();
            var str = '<div class="layui-col-xs12"><label class="layui-form-label">设置方式</label>\n' +
                '                        <div class="layui-input-block layui-col-xs8" style="margin: 0;">\n' +
                '                            <input type="radio" lay-filter="time_type" title="{:lang("全部")}" checked name="time_type" value="0" />\n' +
                '                            <input type="radio" lay-filter="time_type" title="{:lang("按单双日")}" name="time_type" value="1" />\n' +
                '                            <input type="radio" lay-filter="time_type" title="{:lang("按星期")}" name="time_type" value="2" />\n' +
                '                            <input type="radio" lay-filter="time_type" title="{:lang("特殊日期")}" name="time_type" value="3" />\n' +
                '                        </div></div>\n' +
                '<div class="layui-col-xs12" id="selectTimeFormTypeArr"><label class="layui-form-label">&nbsp;</label>\n' +
                '                        <div class="layui-input-block layui-col-xs8" id="single" style="margin: 0;display: none;">\n' +
                '                            <input type="radio" lay-filter="month_value" title="{:lang("每月单日")}" name="month_value" value="8" />\n' +
                '                            <input type="radio" lay-filter="month_value" title="{:lang("每月双日")}" name="month_value" value="9" />\n' +
                '                        </div>\n' +
                '                        <div class="layui-input-block layui-col-xs8" id="week" style="margin: 0;display: none;">\n' +
                '                            <input type="checkbox" lay-skin="primary" lay-filter="xq" title="{:lang("星期一")}" class="time_week" name="week" value="1" />\n' +
                '                            <input type="checkbox" lay-skin="primary" lay-filter="xq" title="{:lang("星期二")}" class="time_week" name="week" value="2" />\n' +
                '                            <input type="checkbox" lay-skin="primary" lay-filter="xq" title="{:lang("星期三")}" class="time_week" name="week" value="3" />\n' +
                '                            <input type="checkbox" lay-skin="primary" lay-filter="xq" title="{:lang("星期四")}" class="time_week" name="week" value="4" />\n' +
                '                            <input type="checkbox" lay-skin="primary" lay-filter="xq" title="{:lang("星期五")}" class="time_week" name="week" value="5" />\n' +
                '                            <input type="checkbox" lay-skin="primary" lay-filter="xq" title="{:lang("星期六")}" class="time_week" name="week" value="6" />\n' +
                '                            <input type="checkbox" lay-skin="primary" lay-filter="xq" title="{:lang("星期日")}" class="time_week" name="week" value="0" />\n' +
                '                        </div>' +
                '                        <div class="layui-input-block layui-col-xs8" id="single" style="margin: 0;display: none;">\n' +
                '                            <input type="radio" lay-filter="month_value" title="{:lang("每月单日")}" name="month_value" value="8" />\n' +
                '                            <input type="radio" lay-filter="month_value" title="{:lang("每月双日")}" name="month_value" value="9" />\n' +
                '                        </div>\n' +
                '<div>\n';
            $('#selectTimeForm').append(str);
        };

        renderSelectTimeForm();
        form.render();
        //初始化隐藏 selectTimeFormTypeArr
        $("#selectTimeFormTypeArr").hide()
        //点击日期类型 切换tab
        function changeTimeType(value){
            if(value==1){
                $("#single").show();
                $("#week").hide();
                $("#moreTimeForm").hide();
                $('#selectSalesDataArr').show();
                $("#selectTimeFormTypeArr").show()
            }else if(value==2){
                $("#single").hide();
                $("#week").show();
                $("#moreTimeForm").hide();
                $('#selectSalesDataArr').show();
                $("#selectTimeFormTypeArr").show()
            }else if(value==3){
                $("#single").hide();
                $("#week").hide();
                $("#moreTimeForm").show();
                $('#selectSalesDataArr').hide();
                $("#selectTimeFormTypeArr").hide()
            }else{
                $("#single").hide();
                $("#week").hide();
                $("#moreTimeForm").hide();
                $('#selectSalesDataArr').show();
                $("#selectTimeFormTypeArr").hide()
            }
        }
        //弹框日期选择
        form.on('radio(time_type)', function(data) {
            var value = data.value;
            changeTimeType(value);
        });
        //弹层单选按钮
        form.on('radio(radio)', function(data) {
            if(data.value == 3) {
                $('#chx').css('display', 'block');
            } else {
                $('#chx').css('display', 'none');
            }
        });
        //切换套餐
        form.on('radio(change_package)',function(data){
            var package_id = data.value;
            $('#setBasePriceBody').show();
            console.log(package_id);
            $.post(basespec_url, {
                'package_id': package_id
            }, function(data) {
                renderPersonList(data);
            });
        })
        //【普通成本】弹窗中时间段
        //添加具体的天数
        var moreTimeList = [];



        //【普通成本】弹窗中规格table渲染
        function renderPersonList(data){
            //渲染规格
            $('.batch_person').html('');
            var sr = '';
            if(data.length < 1){
                sr += '<span style="color: red;line-height: 40px;">请先设置套餐下的规格信息！</span>';
            }else{
                $.each(data, function(i, v) {
                    sr += '<tr date-id="' + v.package_id + '">' +
                        '<td><input readonly type="text" name="person_name" id="person_name" class="layui-input" placeholder="' + v.name + '" value="' + v.name + '"/>' +
                        '<input type="hidden" name="person_id" id="person_id" class="layui-input" value="' + v.id + '"/></td>' +
                        '<td><span class="currency_symbol">'+currency_symbol+'&nbsp;</span><input type="text" data-pid="'+v.id+'" name="total_cost" id="total_cost" class="layui-input package_price_input" autocomplete="off" placeholder="{:lang("结算价")}" value=""/></td>' +
                        '<td><span class="currency_symbol">'+currency_symbol+'&nbsp;</span><input type="text" data-pid="'+v.id+'" name="person_price" id="person_price" class="layui-input package_price_input" autocomplete="off" placeholder="{:lang("建议销售价")}" value=""/></td>' +
                        '<td><input readonly type="text" name="person_num" id="person_num" class="layui-input" placeholder="{:lang("库存")}" value="' + v.num + '" /></td>' +
                        '<td><input readonly type="text" name="minorder_num" id="minorder_num" class="layui-input" placeholder="{:lang("最低下单数")}" value="' + v.minorder_num +'" /></td>' +
                        '<td><input readonly type="text" name="inc_order_num" id="inc_order_num" class="layui-input" placeholder="{:lang("最小增长数")}" value="' + v.inc_order_num +'" /></td></tr>';
                });
            }


            $('.batch_person').html(sr);
            form.render('select');
        }

        //修改售卖日期
        $('.updateSaleTime').click(function(){
            var product_id = $('input[name=product_id]').val();
            var sale_time = $('input[name=sale_time]').val();
            var sale_time = sale_time.split(' - ');
            if(sale_time.length < 2){layer.msg('{:lang("请正确选择售卖日期")}');return false;}
            ajaxUpdateProductSaleTime(product_id,sale_time);
            return false;
        });
        //提交方法
        function ajaxUpdateProductSaleTime(product_id,sale_time)
        {
            var param = {};
            param.id = product_id;
            param.sale_starttime = sale_time[0] || '';
            param.sale_endtime = sale_time[1] || '';
            if(param.sale_starttime > param.sale_endtime){layer.msg('{:lang("售卖起始日期超出售卖终止日期")}');return false;}
            $.post('{:url("admin/product/ajaxUpdateProductInfo")}',param,function (res) {
                layer.msg(res.msg);
                if(res.code > 0){
                    setTimeout(function () {
                        window.location.reload();
                    },1000)
                }
            },'json')
        }
        //切换货币类型自动提交
        form.on('select(currency)',function(res){
            var product_id = $('input[name=product_id]').val();
            var currency = res.value;
            if(currency==undefined || currency==""){layer.msg('{:lang("请正确选择货币类型")}');return false;}
            ajaxUpdateProductCurrency(product_id,currency);
            return false;
        })
        //修改货币类型
        $('.updateCurrency').click(function(){
            var product_id = $('input[name=product_id]').val();
            var currency = $('select[name=currency]').val();
            if(currency==undefined || currency==""){layer.msg('{:lang("请正确选择货币类型")}');return false;}
            ajaxUpdateProductCurrency(product_id,currency);
            return false;
        });
        //提交方法
        function ajaxUpdateProductCurrency(product_id,currency)
        {
            var param = {};
            param.id = product_id;
            param.currency = currency;
            $.post('{:url("admin/product/ajaxUpdateProductInfo")}',param,function (res) {
                layer.msg(res.msg);
                if(res.code > 0){
                    setTimeout(function () {
                        window.location.reload();
                    },1000)
                }
            },'json')
        }
        //提交设置价格
        $('.submitPriceData').click(function(){
            //检查数据是否正确
            //是否选择套餐
            var packageId = $('input[name=select_package_id]').val();
            if(packageId=='' || packageId==undefined){layer.msg('请选择套餐');return false;}
            //是否选择日期
            var saleTime = $('input[name=sale_time]').val();

            if(saleTime=='' || saleTime==undefined){layer.msg('请设置正确的售卖日期');return false;}
            saleTime = saleTime.split(' - ');
            var saleStartTime = saleTime[0] || '';
            var saleEndTime = saleTime[1] || '';
            if(saleStartTime=='' || saleStartTime==undefined || saleEndTime=='' || saleEndTime==undefined || saleStartTime>saleEndTime){layer.msg('请选择正确的时间格式');return false;}

            //是否选择设置方式
            var timeType = $('input[name=time_type]:checked').val();
            if($.inArray(timeType,['0','1','2','3']) < 0){layer.msg('请选择设置方式');return false;}
            //组织日期格式
            var timeValue = [];
            if(timeType=='0' || timeType=='3'){
                timeValue = '';
            }else if(timeType=='1'){
                var monthValue = $('input[name=month_value]:checked').val();
                if(monthValue=='' || monthValue==undefined){layer.msg('请选择每月单双日');return false;}
                timeValue = monthValue;
            }else if(timeType=='2'){
                var weekValue = $("input[name=week]:checked");
                if(weekValue.length<1){
                    layer.msg("{:lang('请选择')} {:lang('日期类型')}");
                    return false;
                }else{
                    $.each(weekValue,function(i,v){
                        timeValue.push($(v).val())
                    });
                    timeValue = timeValue.join(",");
                }
            }
            var moreTimeList = [];
            var moreTimeArr = $("#moreTimeArr a");
            moreTimeArr.each(function (i,v) {
                moreTimeList.push($(v).attr('data-id'));
            })
            var selectDays = [];
            //获取筛选的数据
            if(timeType=='3'){
                //按天设置忽略选择时间
                if(moreTimeList.length < 1){
                    layer.msg('请选择特殊日期');return false;
                }
                selectDays = moreTimeList;
            }else{
                var selectedTime = $("#selectTimeArr a");
                if(selectedTime.length < 1){
                    layer.msg('请正确设置选择日期');return false;
                }
                var fillAllSelectedTime = true;
                var setCurrentSelectedTime = true;
                var selectTimeArr = [];
                $.each(selectedTime,function (i,v) {
                    var selectedTimeValue = $(v).attr('data-id');
                    if(selectedTimeValue=='' || selectedTimeValue==undefined){fillAllSelectedTime = false;return false;}
                    selectedTimeValue = selectedTimeValue.split(' - ');
                    var startTimeValue = selectedTimeValue[0] || '';
                    var endTimeValue = selectedTimeValue[1] || '';
                    if(startTimeValue=='' || startTimeValue==undefined || endTimeValue=='' || endTimeValue==undefined || startTimeValue>endTimeValue){fillAllSelectedTime = false;return false;}
                    if(startTimeValue < saleStartTime || endTimeValue > saleEndTime){setCurrentSelectedTime = false;return false;}
                    selectTimeArr.push({startTime:startTimeValue,endTime:endTimeValue});
                })
                if(!fillAllSelectedTime){
                    layer.msg('请正确设置选择日期');return false;
                }
                if(!setCurrentSelectedTime){
                    layer.msg('请在售卖日期范围内选择日期');return false;
                }
                console.log(selectTimeArr)
                selectDays = getDaysByDates(selectTimeArr,parseInt(timeType),timeValue);
                //2020.10.16 特殊日期与其他设置方式不共存 故不合并
                // if(moreTimeList.length>0){
                //     for(var i=0;i<moreTimeList.length;i++){
                //         //moreTimeList 元素不存在于 selectDays 则添加
                //         if($.inArray(moreTimeList[i],selectDays)<0){
                //             selectDays.push(moreTimeList[i]);
                //         }
                //     }
                // }
            }

            if(selectDays.length < 1){
                layer.msg("{:lang('您选择的时间段中没有时间被选择')}");
                return false;
            }

            //表单数据
            var costData = $('.batch_person input[name=total_cost]');
            var costArr = [];
            var priceArr = [];
            //是否填写了所有价格数据
            var noCostValueFlag = false;
            $.each(costData,function (i,v) {
                var cost = $(v).val();
                var price = $(v).parent().parent().find('input[name=person_price]').val();
                if(cost=='' || cost==undefined){
                    noCostValueFlag = true;return false;
                }else{
                    var spec_id = $(v).attr('data-pid');
                    price = price==undefined||price==''?0:price;
                    priceArr.push({'spec_id':spec_id,'price':price,'total_cost':cost});
                }
            })
            if(noCostValueFlag){layer.msg('{:lang("请填写所有的结算价")}！');return false;}
            var product_id = $('input[name=product_id]').val();

            //提交数据
            $.post('{:url("admin/product/ajaxSetProductBasePrice")}',{product_id:product_id,date:selectDays,price:priceArr},function(res){
                layer.msg(res.msg);
                if(res.code > 0){
                    //刷新当前页面
                    setTimeout(function(){
                        window.location.reload();
                    },1000)
                }
            },'json')
            return false;
        })
        //根据设置方式返回日期
        function getDaysByDates(selectTimeArr,time_type,time_value){
            if(selectTimeArr.length < 1){ return false; }
            var dateArray = [];
            $.each(selectTimeArr,function (i,v) {
                var s1 = v.startTime.split("-");
                var s2 = v.endTime.split("-");
                var monthCount = 0;
                if(parseInt(s1[0]) < parseInt(s2[0])) {
                    monthCount = (parseInt(s2[0]) - parseInt(s1[0])) * 12 + parseInt(s2[1]) - parseInt(s1[1]) + 1;
                } else {
                    monthCount = parseInt(s2[1]) - parseInt(s1[1]) + 1;
                }
                var stime= new Date(v.startTime+' 00:00:00').getTime()-1000;
                var etime= new Date(v.endTime+' 23:59:59').getTime();
                if(monthCount > 0) {
                    var startM = parseInt(s1[1]);
                    var startY = parseInt(s1[0]);
                    for(var i = 0; i < monthCount; i++) {
                        var da = new Date(startY, startM, 0);
                        //获取每月有多少天
                        var day = da.getDate(); //获取当前月有多少天
                        for(j = 1; j <= day; j++) {
                            var the_day = startY + "-" + (startM > 9 ? startM : "0" + startM) + "-" + (j > 9 ? j : "0" + j);
                            //如果日期已存在数组中 则跳过进入下一次循环
                            if($.inArray(the_day,dateArray) > -1){
                                continue;
                            }
                            var curtime = new Date(startY + '-' + startM + '-' + j + ' 00:00:00');
                            var curtime = curtime.getTime();
                            if(curtime < stime || curtime > etime){
                                continue;
                            }
                            if (time_type == 0) {
                                dateArray.push(the_day);
                            } else if(time_type ==1) {
                                //单日
                                if (j % 2 == 1 && time_value == '8') {
                                    dateArray.push(the_day);
                                } else if (j % 2 == 0 && time_value == '9') {
                                    //双日
                                    dateArray.push(the_day);
                                }
                            }else if(time_type ==2){
                                //周
                                var value = time_value.split(",");
                                var w = new Date(startY + '-' + startM + '-' + j)
                                var the_week = w.getDay();
                                var index= value.indexOf(String(the_week));
                                if ( index > -1) {
                                    dateArray.push(the_day);
                                }
                            }
                        }
                        if(startM<12){
                            startM += 1;
                        }else{
                            startM = 1;
                            startY += 1;
                        }
                    }
                }
                console.log(dateArray)
            })
            return dateArray.sort();
        }

        $('.setBasePackage').click(function(){
            var product_id = $('input[name=product_id]').val();
            layer.open({
                type:2,
                title:'设置套餐',
                content:'{:url("admin/product/setbasepackage")}?id='+product_id,
                area:['80%','80%'],
                end:function(){
                    location.reload();
                }
            });
        })

        function addNewSelectTime(time_str){
            if(time_str=="" || time_str==undefined){
                layer.msg("请选择日期");return false;
            }
            var selectTimeList = [];
            var str = '';
            var selectTimeArr = $("#selectTimeArr a");
            selectTimeArr.each(function (i,v) {
                selectTimeList.push($(v).attr('data-id'));
            })
            if(selectTimeList.length < 1){
                //直接插入
                str = '<a class="layui-btn layui-btn-sm layui-bg-cyan deleteSelectTime" data-id="'+time_str+'" style="margin:8px;">'+time_str+' <i class="layui-icon">&#x1006;</i></a>\n';
            }else{
                //判断是否存在
                if($.inArray(time_str,selectTimeList)>-1){
                    //存在 跳过
                    layer.msg("请勿重复添加日期");return false;
                }else{
                    //不存在 插入
                    str = '<a class="layui-btn layui-btn-sm layui-bg-cyan deleteSelectTime" data-id="'+time_str+'" style="margin:8px;">'+time_str+' <i class="layui-icon">&#x1006;</i></a>\n';
                }
            }
            if(str==""){
                layer.msg("请选择日期");return false;
            }
            $("#selectTimeArr").append(str);
        }

        function addNewMoreTime(time_str){
            if(time_str=="" || time_str==undefined){
                layer.msg("请选择日期");return false;
            }
            var moreTimeList = [];
            var str = '';
            var moreTimeArr = $("#moreTimeArr a");
            moreTimeArr.each(function (i,v) {
                moreTimeList.push($(v).attr('data-id'));
            })
            if(moreTimeList.length < 1){
                //直接插入
                str = '<a class="layui-btn layui-btn-sm layui-bg-cyan delMoreTime" data-id="'+time_str+'" style="margin:8px;">'+time_str+' <i class="layui-icon">&#x1006;</i></a>\n';
            }else{
                //判断是否存在
                if($.inArray(time_str,moreTimeList)>-1){
                    //存在 跳过
                    layer.msg("请勿重复添加特殊日期");return false;
                }else{
                    //不存在 插入
                    str = '<a class="layui-btn layui-btn-sm layui-bg-cyan delMoreTime" data-id="'+time_str+'" style="margin:8px;">'+time_str+' <i class="layui-icon">&#x1006;</i></a>\n';
                }
            }
            if(str==""){
                layer.msg("请选择日期");return false;
            }
            $("#moreTimeArr").append(str);
        };

        $(document).on('click','.deleteSelectTime',function(){
            $(this).remove();
        })
        //删除具体的天数
        $(document).on('click','.delMoreTime',function(){
            $(this).remove();
        });
    });

</script>

<!-- 查看价格 -->
<div class="layui-container" id="showPrice" style="padding: 15px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <blockquote class="layui-elem-quote elem-quote-div">
                <span>产品基础价格展示</span>
            </blockquote>
            <div class="layui-row package-list-div">
                <div class="layui-inline" style="width: 100px;text-align: center">
                    展示套餐
                </div>
                <div class="layui-inline">
                    <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                        <ul class="layui-tab-title" id="packages">
                            {if !empty($packageList)}
                            {volist name='packageList' id='package_v'}
                            <li data-id="{$package_v.id}" class="getPackagePrice">{$package_v.name}</li>
                            {/volist}
                            {else}
                            <span style="line-height: 40px;color:red" class="layui-input-inline">请先设置套餐！</span>
                            {/if}
                        </ul>
                    </div>
                </div>
            </div>
            <div class="layui-row package-list-div">
                <div class="layui-inline" style="width: 100px;text-align: center">
                    展示月份
                </div>
                <div class="layui-inline">
                    <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                        <ul class="layui-tab-title" id="months">

                        </ul>
                    </div>
                </div>
            </div>


            <div class="layui-inline" id="test-n2" ></div>
        </div>
    </div>

    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief" id="showPackageData">

            </div>
        </div>
    </div>
</div>
<!--用于删除产品价格设置-->
<div style="padding: 15px;display: none;" id="delBasePriceContent">
    <div class="layui-row">
        <div class="layui-col-md12">
            <form class="layui-form" action="" method="post" id="delBasePriceForm">
                    <div class="layui-form-item">
                        <label class="layui-form-label">{:lang('选择日期')}</label>
                        <div class="layui-input-inline layui-col-md8 noMarginLeft">
                            <input type="text" name="del_time" value="" class="layui-input del_time" />
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">选择套餐<br>[多选]</label>
                        <div class="layui-input-block layui-col-md8 noMarginLeft">
                            {volist name='packageList' id='package_v'}
                            <input type="checkbox" name="select_del_package_id[]" value="{$package_v['id']}" title="{$package_v['name']}" class="layui-input"/>
                            {/volist}

                        </div>
                        <div class="layui-input-block layui-col-md8 noMarginLeft" style="margin-top: 10px">
                            <a class="layui-btn layui-btn-primary layui-btn-sm selectAll">全选</a>
                            <a class="layui-btn layui-btn-primary layui-btn-sm selectAllCancel">取消全选</a>
                        </div>
                    </div>
                </form>
        </div>
    </div>
</div>
<script>
    layui.use(['layer', 'form','jquery','laydate','element'], function() {
        var layer = layui.layer,
            $ = layui.jquery,
            laydate = layui.laydate,
            element = layui.element,
            form = layui.form;
        //定义json
        var data={};
        var select_year_month='';
        var new_date = new Date();
        console.log(new_date)
        loding_date(new_date ,data);
        //组装日历单元格内容
        function formatCalendarPrice(data)
        {
            var currency_symbol = "{$product.currency_symbol | default='￥'}";
            var format_data = [];
            if(data.length>0){
                $.each(data,function(i,v){
                    var day = v.time.split('-')[2];
                    format_data[v.time] = "<div class='calendar_day'>"+day+"</div><div class='calendar_price'>"+currency_symbol+v.cost+"</div>";
                })
            }
            console.log(format_data);
            return format_data;
        }
        //初始化 日历内容
        function initCalendarContent(){
            var sale_starttime = "{$product.sale_starttime|date='Y-m-d',###}";
            if(sale_starttime==''){return fasle;}
            sale_starttime_arr = sale_starttime.split('-');
            var year = sale_starttime_arr[0] || '';
            var month = sale_starttime_arr[1] || '';
            if(year=='' || month==''){return fasle;}
            select_year_month = year+'-'+month;
            getDailypriceByMonth(year,month,sale_starttime);
        }
        //initCalendarContent();
        //根据月份获取套餐信息
        function getDailypriceByMonth(year,month,obj_date)
        {
            var product_id = $('input[name=product_id]').val();
            $.post("{:url('admin/product/getBaseDailypriceByMonth')}",{year:year,month:month,product_id:product_id},function(res){
                if(res.data.length<1){layer.msg('暂无更多数据');return false;}
                var formatData = formatCalendarPrice(res.data);
                $('#test-n2').html('');//重要！由于插件是嵌套指定容器，再次调用前需要清空原日历控件
                loding_date(obj_date ,formatData);
            },'json')
        }
        var packageMonthData = [];
        var monthPrcieData = [];
        var priceData = [];
        var isRenderPriceData = false;
        //根据套餐获取月份
        function getPackageMonth(package_id)
        {
            if(package_id=='' || package_id==undefined){layer.msg('请先选择套餐！');return false;}
            if(packageMonthData.hasOwnProperty(package_id )){
                renderPackageMonthData(packageMonthData[package_id],package_id);
            }else{
                var loading = layer.load(2);
                $.post("{:url('admin/product/getSaleMonthByPackageId')}",{package_id:package_id},function(res){
                    layer.close(loading);
                    if(res.code>0){
                        packageMonthData[package_id] = res.data;
                        renderPackageMonthData(res.data,package_id);
                    }else{
                        layer.msg(res.msg);
                    }
                },'json')
            }
        }
        function renderPackageMonthData(data,package_id){
            //渲染月份
            $("#months").children().remove();
            var month_html = '';
            if(data.length>0){
                $.each(data,function(i,v){
                    month_html += '<li class="getPriceByMonthAndPackageId" data-year="'+v.year+'" data-month="'+v.month+'" data-pid="'+package_id+'">'+v.show_date+'</li>';
                })
            }else{
                month_html = '<li style="color:red">暂未设置价格！</li>';
            }

            $("#months").append(month_html);
            //清空日历
            $('#test-n2').html('');//重要！由于插件是嵌套指定容器，再次调用前需要清空原日历控件
            var new_date = new Date();
            loding_date(new_date ,[]);
            //重置日历 隐藏具体套餐信息
            $("#showPackageData").hide();
        }
        //根据月份获取套餐日历
        function getMonthPriceh(package_id,year,month)
        {
            var obj_date = year + '-' + month + '-' + '01';
            if(monthPrcieData.hasOwnProperty(package_id + '-' + year + '-' + month)){
                renderMonthPriceData(monthPrcieData[package_id + '-' + year + '-' + month],obj_date);
            }else{
                if(package_id==undefined || package_id==''){return false;}
                var loading = layer.load(2);
                $.post("{:url('admin/product/getSalePriceByPackageIdAndMonth')}",{package_id:package_id,year:year,month:month},function(res){
                    layer.close(loading);
                    if(res.code>0){
                        monthPrcieData[package_id+'-'+year+'-'+month] = res.data;
                        console.log(monthPrcieData)
                        renderMonthPriceData(res.data,obj_date)
                    }else{
                        layer.msg(res.msg);
                    }
                },'json')
            }
        }
        //渲染套餐日历
        function renderMonthPriceData(data,obj_date)
        {
            //渲染日历
            if(data.length<1){layer.msg('暂无更多数据');return false;}
            var formatData = formatCalendarPrice(data);
            $('#test-n2').html('');//重要！由于插件是嵌套指定容器，再次调用前需要清空原日历控件
            loding_date(obj_date ,formatData);
            if(!isRenderPriceData){
                $('body,html').animate({ scrollTop: 600},800);
            }else{
                isRenderPriceData = false;
            }
        }
        //根据日期获取套餐信息
        function getBaseDailypriceByDate(date)
        {
            var package_id = $("#packages .layui-this").attr('data-id');
            if(package_id==undefined || package_id==''){
                return false;
            }
            if(priceData.hasOwnProperty(package_id + '-' + date)){
                renderPackageData(priceData[package_id + '-' + date],date);
            }else{
                $.post("{:url('admin/product/getBaseDailypriceByDate')}",{date:date,package_id:package_id},function(res){
                    if(res.data.length<1){$("#showPackageData").hide();layer.msg('暂未设置价格');return false;}
                    //渲染套餐列表
                    priceData[package_id + '-' + date] = res.data;
                    console.log(priceData);
                    renderPackageData(res.data,date);
                },'json')
            }
        }
        //渲染套餐列表
        function renderPackageData(data,date)
        {
            //防止多次点击
            $("#showPackageData").show();
            //先清空内容
            $("#showPackageData").html('');
            var html = '<blockquote class="layui-elem-quote"><span>套餐信息展示</span><span>【当前日期:'+date+'】</span></blockquote>';
            html += '<div class="layui-tab-content">';
            html += '<div class="layui-tab-item layui-show">';
            html+= '<table class="layui-table"><thead><tr><th>名称</th><th>结算价</th><th>建议销售价</th><th>库存</th><th>最低下单</th><th>最小增长</th><th>操作</th></tr></thead><tbody>';
            $.each(data,function(ii,vv){
                html+='<tr><td>'+vv.name+'</td><td>' +
                    '<span class="currency_symbol">'+currency_symbol+'&nbsp;</span><input type="text" class="layui-input currency_symbol" style="width:80%;" name="total_cost" value="'+vv.total_cost+'"></td><td>' +
                    '<span class="currency_symbol">'+currency_symbol+'&nbsp;</span><input type="text" class="layui-input currency_symbol" style="width:80%;"  name="person_price" value="'+vv.price+'">' +
                    '</td><td>'+vv.num+'</td><td>'+vv.minorder_num+'</td><td>'+vv.inc_order_num+'</td><td>' +
                    '<button class="layui-btn layui-btn-xs layui-btn-normal setSingleDayBasePrice" data-date="'+date+'" data-id="'+vv.id+'">修改</button>' +
                    '</td></tr>';
            })
            html += '</tbody>';
            html += '</table>';
            html += '</div>';
            html += '</div>';
            $("#showPackageData").append(html);
            isRenderPriceData = true;
            $('body,html').animate({ scrollTop: 800},800);
        }
        $(document).on('click','.setSingleDayBasePrice',function(){
            var price = $(this).parent().parent().find('input[name=person_price]').val();
            var total_cost = $(this).parent().parent().find('input[name=total_cost]').val();
            var id = $(this).attr('data-id');
            var date = $(this).attr('data-date');
            if(price=='' || price==undefined){layer.msg('请填写价格!');return false;}
            $.post("{:url('admin/product/setSingleDayBasePrice')}",{dailyprice_id:id,price:price,total_cost:total_cost},function (res) {
                layer.msg(res.msg);
                //删除缓存的对应的单日套餐信息
                var package_id = $("#packages layui-this").attr('data-id');
                delete packageData[package_id +'-'+date];
                console.log(packageData);
            },'json')
        })
        //日历插件调用方法
        function loding_date(date_value,data){

            laydate.render({
                elem: '#test-n2'
                ,type: 'date'
                ,theme: 'grid'
                ,min: '{$product.sale_starttime|date="Y-m-d",###}'
                ,max: '{$product.sale_endtime|date="Y-m-d",###}'
                ,position: 'static'
                ,range: false
                ,value:date_value
                ,calendar: true
                ,btns:false
                ,done: function(value, date, endDate){
                    console.log(value); //得到日期生成的值，如：2017-08-18
                    console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                    console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                    //layer.msg(value)

                    //调用弹出层方法
                    //date_chose(value,data);
                    //获取详细日期的套餐信息
                    getBaseDailypriceByDate(value);

                }
                , mark:data//重要json！
                ,change: function(value, date){
                    if(select_year_month!=date.year + '-' + date.month){
                        select_year_month = date.year + '-' + date.month;
                        var package_id = $("#packages .layui-this").attr('data-id');
                        getMonthPriceh(package_id,date.year,date.month)
                    }
                }
            });
        }

        //批量删除
        $('.delBasePrice').click(function(){
            layer.open({
                type:1,
                title:'批量删除价格',
                area:['40%','50%'],
                btn:['{:lang("提交")}','{:lang("取消")}'],
                content:$("#delBasePriceContent"),
                yes:function(){
                    var product_id = $('input[name=product_id]').val();
                    //检查输入的日期
                    var del_time = $("input[name=del_time]").val();
                    var del_time_arr = del_time.split(' - ');
                    var start_del_time = del_time_arr[0] || '';
                    var end_del_time = del_time_arr[1] || '';
                    if(start_del_time=='' || end_del_time==''){layer.msg('请正确选择日期!');return false;}
                    //检查选择的套餐
                    var select_ids = [];
                    $.each($("#delBasePriceForm input[type=checkbox]:checked"),function(i,v){
                        select_ids.push($(v).val());
                    })
                    if(select_ids.length<1){layer.msg('请选择套餐');return false;}
                    $.post("{:url('admin/product/delBasePriceByDate')}",{product_id:product_id,start_time:start_del_time,end_time:end_del_time,package_ids:select_ids},function(res){
                        layer.msg(res.msg);
                        if(res.code>0){
                            setTimeout(function(){
                                window.location.reload();
                            },1000)
                        }
                    },'json')
                }
            })
        })
        //全选
        $(".selectAll").click(function(){
            $("#delBasePriceForm input[type=checkbox]").prop('checked','checked');
            form.render('checkbox');
        })
        //取消全选
        $(".selectAllCancel").click(function(){
            $("#delBasePriceForm input[type=checkbox]").prop('checked',false);
            form.render('checkbox');
        })

        //点击套餐获取售卖月份和日历价格
        $(".getPackagePrice").click(function(){
            var package_id = $(this).attr('data-id');
            if(package_id=='' || package_id==undefined){layer.msg('请先选择套餐！');return false;}
            getPackageMonth(package_id)
        })
        //点击月份获得日历价格
        $(document).on('click',".getPriceByMonthAndPackageId",function(){
//            console.log('123');return false;
            var package_id = $(this).attr('data-pid');
            var year = $(this).attr('data-year');
            var month = $(this).attr('data-month');
            if(package_id=='' || package_id==undefined){layer.msg('请先选择套餐！');return false;}
            getMonthPriceh(package_id,year,month)
        })
        //去除红色边框
        $(document).on('input','.specsPriceSnap .package_price_input',function(){
            if($(this).val()==''){
                $(this).css('border-color',"red");
            }else{
                $(this).css('border-color',"#D2D2D2");
            }
        })
        //延迟1s加载
        setTimeout(function(){
            firstLoadPackageData();
        },500)
        //默认加载第一个套餐的第一个月数据
        function firstLoadPackageData()
        {
            $("#packages li:first").click();
            setTimeout(function(){
                firstLoadMonthData();
            },500)
        }
        function firstLoadMonthData()
        {
            $("#months li:first").click();
        }
    });</script>
</body>
</html>
